import store from '@/store'
import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'

const tokenTime = 10000
function isCheckTimeOut() {
  const time2 = Date.now()
  const timestamp = (time2 - store.getters.hrsaasTime) / 1000
  return timestamp > tokenTime
}

const service = axios.create({
  baseURL: '/api',
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(config => {
  // console.log(config)
  // 接口 具有公用性字段在这添加
  // Authorization
  // Bearer b31747f8-7344-4d4a-a1b2-ad0b22dfda19
  if (store.getters.token) {
    if (isCheckTimeOut()) {
      // alert('超时了')
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('超时了，请重新登录'))
    }
    config.headers.Authorization = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(response => {
  console.log(response)
  const { data, message, success } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, error => {
  console.log(error)
  console.log(error.response)
  if (error && error.response.status === 401) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error(error.response.data.message || 'token 失效， 请重新登录')
  } else {
    Message.error(error.message || '后端报错')
  }
  return Promise.reject(error)
})

export default service
